import React, {memo, useEffect, useState} from 'react';
import CommentShowListStyle from "./CommentShowListStyle";
import {getCommentsListByIdApi, insertCommentApi} from "../../../services/comments";
import {CommentsListItem, CommentsListObject} from "../../../interface/CommentsInterface";
import {dateFormat, format} from "../../../utils/dateFormat";
import {Button, Form, FormProps, Input, message} from "antd";
import {useForm} from "antd/es/form/Form";

/**
 * 时间: 2024年1月29日 13点38分
 * 评论列表展示组件
 * props说明
 *  id,根据id查询评论列表,并进行展示,
 *  不传入或者列表长度为0是,显示暂无数据
 * 我们这里不再写关于回复的功能了,那样系统就会更加复杂
 *
 */
type Props = {
  commentId?:number,
  type?:number,
};
type FieldType = {
  content?: string;
};
export default memo(function (props: Props) {
  //获取form表单对象
  const [form] = useForm();
  const [messageApi, contextHolder] = message.useMessage();
  const [commentListObject,setCommentListObject]=useState<CommentsListObject>({});

  //表单规则匹配时执行
  const onFinish: FormProps<FieldType>["onFinish"] = (values) => {
    //成功时获取当前登录的用户id和目标id
    const userId=parseInt(localStorage.getItem("yf_gaduation_zzmusic_user_id") as string)
    /** 新增评论方法 */
    insertCommentApi({
      targetId:props.commentId as number,
      type:props.type as number,
      content:values.content,
      userId,
    }).then((result:any)=>{
      if (result.data.code===200){
        //清空评论
        form.resetFields();
        messageApi.open({
          type: 'success',
          content: '评论发送成功',
        });
        //重新请求数据
        getCommentsList();

      }else{
        messageApi.open({
          type: 'error',
          content: result.data.msg,
        });
      }
    },(error)=>{
      console.log(error);
    });
  };

  //表单规则不匹配时执行
  const onFinishFailed: FormProps<FieldType>["onFinishFailed"] = (errorInfo) => {
    console.log('Failed:', errorInfo);
  };

  useEffect(() => {
    getCommentsList();
  }, []);

  //获取评论列表方法
  function getCommentsList(){
    getCommentsListByIdApi({targetId:props.commentId,type:props.type}).then((result:any)=>{
      setCommentListObject(result.data.data);
    },(error)=>{
      console.log(error);
    });
  }

  return (
    <CommentShowListStyle>
      {contextHolder}
      <h3 className="comm-head">留下评论，感动生活</h3>
      <Form
        form={form}
        className={"comment_form"}
        name="basic"
        labelCol={{ span: 8 }}
        wrapperCol={{ span: 16 }}
        initialValues={{ remember: true }}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
        autoComplete="off"
      >
        <div className="comm-input">
          <div className="foot">
            <Form.Item<FieldType>
              className="form_item"
              name="content"
              rules={[{ required: true, message: '请输入你的评论内容' }]}
            >
              <Input.TextArea />
            </Form.Item>
            <Form.Item className="btn">
              <Button type="primary" htmlType="submit">
                发表评论
              </Button>
            </Form.Item>
          </div>
        </div>
      </Form>
      <h3 className="comm-head hot">
        精彩评论<sub id="comm_num">({commentListObject.total})</sub>
        {/*<span className="yl_span default active">默认</span>*/}
        {/*<span className="yl_span upTime">时间升序</span>*/}
        {/*<span className="yl_span downTime">时间降序</span>*/}
      </h3>
      {/* style="background-image: url('https://static.youku.com/lvip/img/avatar/310/6.png');"*/}
      <ul className="comm-list">
        {
          commentListObject.data?.map((item:CommentsListItem,index)=>{
            return(
              <li className="comm-item" key={index}>
                <div className="avatar"
                  style={{backgroundImage:`url(${item.cover?item.cover:'https://bucket-yufei.oss-cn-beijing.aliyuncs.com/sixth-qianfeng/back/weidenglu.png'})`}}
                ></div>
                <div className="info">
                  <p className="name vip">
                    {item.nickname}
                  </p>
                  <p className="time">
                    <span>{dateFormat(item.sendTimer)}</span>
                    <span className="iconfont icon-collect"></span>
                    <span className="iconfont icon-collect-sel"></span>
                  </p>
                  <p>
                    {item.content}
                  </p>
                </div>
              </li>
            )
          })
        }
      </ul>

    </CommentShowListStyle>
  );
});
